# -*- encoding=utf8 -*-
__author__ = "Administrator"


from airtest.core.api import *
from airtest.aircv.aircv import *
from airtest.core.cv import *
from airtest.aircv.template import *
from airtest.utils.logger import get_logger
import random

auto_setup(__file__)
def height_width():
    global width
    global height
    global x_min
    global y_min
    global x_max
    global y_max
    global half_num
    if G.DEVICE.display_info['orientation'] in [1,3]:        
        height = G.DEVICE.display_info['width']        
        width = G.DEVICE.display_info['height']
    else:
        height = G.DEVICE.display_info['height']
        width = G.DEVICE.display_info['width']
    half_num = (0.5*width,0.5*height)
    x_min =width/4
    y_min =height/4
    x_max = width/4*3
    y_max = height/4*3
    return [height,width] 
def h_w_num(num_01,num_02):
    return (num_01*width,num_02*height)
def h_w_num_min_max(num_01,num_02):
    return ((1+num_01)*(width/2),(1+num_02)*(height/2))
def true_touch(v):
    if exists(v):
        random_price(v)
def search_equal(sleep_num):    
    screen_01 = G.DEVICE.snapshot()  #截图到内存
    #图片裁切
    sleep(sleep_num)
    screen_02 = G.DEVICE.snapshot()
    predict_screen_01 = aircv.crop_image(screen_01, (x_min, y_min, x_max, y_max))
    predict_screen_02 = aircv.crop_image(screen_02, (x_min, y_min, x_max, y_max))
    like_num = find_template(predict_screen_01,predict_screen_02,-1)['confidence']
    LOGGING.debug("当前相似度 : %s" % like_num)
#     print("当前相似度：" , like_num)
    if like_num >0.92:
        return True
    else:
        return False

def random_price(v):
    v.target_pos=1
    [min_x_one,min_y_one] = exists(v)
    v.target_pos=9
    [max_x_nine,max_y_nine] = exists(v)    
    random_x = random.random()    
    random_y = random.random()
    num_x_tiaozhan =(max_x_nine-min_x_one)*random_x + min_x_one;
    num_y_tiaozhan =(max_y_nine-min_y_one)*random_y +min_y_one;
    LOGGING.debug("当前随机坐标为 : （%s,%s）" % (num_x_tiaozhan,num_y_tiaozhan))
    touch(v =(num_x_tiaozhan,num_y_tiaozhan))      
def start_yys():
    while True:
        true_touch(Template(r"tpl1601286329889.png", record_pos=(-0.003, 0.045), resolution=(960, 540)))
        sleep(random.uniform(2,5))           
        num_x_n = random.random();
        num_y_n = random.random();
        LOGGING.debug("当前随机坐标为 : （%s,%s）" % (num_x_n,num_y_n))
        touch(h_w_num_min_max(num_x_n,num_y_n))    
        
        result_tiaozhan = exists(Template(r"tpl1601192029774.png", record_pos=(0.421, 0.211), resolution=(960, 540)))
        if result_tiaozhan:
            
            random_price(Template(r"tpl1601192029774.png", record_pos=(0.421, 0.211), resolution=(960, 540)))
            sleep(random.uniform(120,130))
            while True:
                result_stop = search_equal(3)
                if result_stop:
                    break
height_width()
start_yys()


